package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.config.exceptionhandler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author ct_start
 * @since 2021-08-12
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {
    @Autowired
    private EduVideoService videoService;

    // 注入远程服务调用的Interface
    @Autowired
    VodClient vodClient;

    // 根据章节id 查询所有小节
    @GetMapping("FindAllVideo/{ChapterId}")
    public R FindAllVideo(@PathVariable String ChapterId){

         List <EduVideo>list =videoService.FindAllByChapterId(ChapterId);
        return  R.ok().data("VideoList",list);
    }

    // 根据小节id 查询小节
    @GetMapping("{id}")
    public R GetVideoById(@PathVariable String id){

        EduVideo eduVideo1 = videoService.getById(id);

        return  R.ok().data("eduVideo",eduVideo1);
    }


    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        videoService.save(eduVideo);
        return R.ok();
    }

    //删除小节
    //  后面这个方法需要完善：删除小节时候，同时把里面视频删除(指的是阿里云里面的视频 )
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id) {
        // 还需要根据小节Id 查询里面的视频ID
        EduVideo eduVideo = videoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        if (!StringUtils.isEmpty(videoSourceId)){ // 用工具类是为了防止空指针 真是细节
            R r = vodClient.removeAlyVideo(videoSourceId);
            if (r.getCode()==20001){
                throw  new GuliException(20001,"删除视频失败,熔断器");
            }

        }
            videoService.removeById(id);
        return R.ok();
    }



    // 修改小节
    @PostMapping("UpdateVideo")
    public  R UpdateVideo(@RequestBody EduVideo eduVideo){

        videoService.updateById(eduVideo);
        return  R.ok();
    }

}

